﻿using DevExpress.XtraBars.Alerter;
using DevExpress.XtraEditors;
using DevExpress.XtraTab;
using EkStudio.com.bean.xml.BillChart;
using EkStudio.com.bean.xml.BillDictionary;
using EkStudio.com.bean.xml.BillMapping;
using EkStudio.com.bean.xml.BillModule;
using EkStudio.com.bean.xml.BillMultiple;
using EkStudio.com.bean.xml.BillReflect;
using EkStudio.com.bean.xml.ProjectMenu;
using EkStudio.com.bean.xml.ProjectVersion;
using EkStudio.com.bean.xml.reflection.JAXB;
using EkStudio.com.bean.xml.RootInterface;
using EkStudio.com.bean.xml.RootInterface.Plugin;
using EkStudio.com.bean.xml.Unit;
using EkStudio.com.bean.xml.WorkFlow;
using EkStudio.com.bean.xml.WorkFlow.Node;
using EkStudio.com.common.clipboard;
using EkStudio.com.common.dbconn;
using EkStudio.com.common.session;
using EkStudio.com.common.unit;
using EkStudio.com.ui.form;
using EkStudio.com.ui.form.AllowLogin;
using EkStudio.com.ui.unitbill;
using EkStudio.com.ui.unitbill.property.Event;
using EkStudio.Com.UI.Interface;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Xml;

namespace EkStudio
{
    public partial class ProjectRootPanel :XtraUserControl, ProjectRootInterface
    {

        private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(ProjectRootPanel));

        private User user = null;

        private HttpConnectUnit http = null;
        private ProjectMenuItem menuItem = null;
        private ProjectVersionItem projectVersion = null;

        /// <summary>
        /// 当前激活的子窗口
        /// </summary>
        private ProjectUnitBillInterface ActiveBill = null;

        private List<ProjectUnitBillInterface> BillList = new List<ProjectUnitBillInterface>();

        public FormMain RootForm = null;

        private int ThreadFormId = -1;

        private bool loadding = false;
        private string willOpenKey = "";//正在打开的单据key
        private string willOpenCaption = "";//正在打开的单据caption
        private int willOpenType = -1;//正在打开的单据类型
        private bool willReadOnly = false;//下在打开的单据是否只读


        public ProjectRootPanel(FormMain _form, HttpConnectUnit _http)
        {
            InitializeComponent();
            RootForm = _form;
            http = _http;
            ThreadFormId = Thread.CurrentThread.ManagedThreadId;//获取当前线程ID
        }
        /// <summary>
        /// 加载目录
        /// </summary>
        public void InitMenu()
        {
            RootForm.ChangedCmdStatus("加载帐套列表配置...");
            loadding = true;
            willOpenCaption = "目录";
            willOpenKey = "ProjectMenu";
            willOpenType = ProjectUtil.TYPE_PROJECT_MENU;
            bool ReadOnly = false;
            http.AsyncResourcesXmlBean("ProjectMenu", "目录", ProjectUtil.TYPE_PROJECT_MENU, ref ReadOnly, null, LoadXmlBean);
        }
        /// <summary>
        /// 初始化帐套配置
        /// </summary>
        private void InitProjectVersion()
        {
            RootForm.ChangedCmdStatus("加载帐套全局配置...");
            loadding = true;
            willOpenCaption = "配置";
            willOpenKey = "ProjectVersion";
            willOpenType = ProjectUtil.TYPE_PROJECT_VERSION;
            bool ReadOnly = false;
            http.AsyncResourcesXmlBean("ProjectVersion", "配置", ProjectUtil.TYPE_PROJECT_VERSION, ref ReadOnly, null, LoadXmlBean);
        }

        private void ReLoadMenu()
        {
            MenuTreeView.Nodes.Clear();

            //加载目录
            TreeNode TreeRoot = new TreeNode();
            TreeRoot.Name = "TreeRoot";
            TreeRoot.ImageIndex = 3;
            TreeRoot.SelectedImageIndex = 3;
            TreeRoot.Text = "业务模型结构设计";
            TreeRoot.Tag = 0;

            //加载字典
            TreeNode DicTreeRoot = new TreeNode();
            DicTreeRoot.ImageIndex = 4;
            DicTreeRoot.SelectedImageIndex = 4;
            DicTreeRoot.Name = "DicTreeRoot";
            DicTreeRoot.Text = "业务字典";
            DicTreeRoot.Tag = ProjectUtil.TYPE_DIC_MODULE_ROOT;

            if (MenuItem.Dictionary != null && MenuItem.Dictionary.Module != null && MenuItem.Dictionary.Module.Count > 0)
            {
                for (int i = 0; i < MenuItem.Dictionary.Module.Count; i++)
                {
                    ProjectMenuCommonElement it = MenuItem.Dictionary.Module[i];
                    TreeNode node = new TreeNode();
                    node.ImageIndex = 7;
                    node.SelectedImageIndex = 7;
                    node.Text = it.Caption;
                    node.Name = it.Command;
                    node.Tag = ProjectUtil.TYPE_DIC_MODULE;
                    DicTreeRoot.Nodes.Add(node);
                }
            }
            TreeRoot.Nodes.Add(DicTreeRoot);

            //加载模块
            TreeNode ModTreeRoot = new TreeNode();
            ModTreeRoot.ImageIndex = 5;
            ModTreeRoot.SelectedImageIndex = 5;
            ModTreeRoot.Text = "业务单据";
            ModTreeRoot.Tag = ProjectUtil.TYPE_BILL_MODULE_ROOT;
            if (MenuItem.Business != null && MenuItem.Business.Modules != null && MenuItem.Business.Modules.Count > 0)
            {
                for (int i = 0; i < MenuItem.Business.Modules.Count; i++)
                {
                    ProjectMenuModGroup group = MenuItem.Business.Modules[i];
                    TreeNode node = new TreeNode();
                    node.Text = group.Caption;
                    node.Tag = ProjectUtil.TYPE_BILL_MODULE_GROUP;
                    node.Name = group.Key;

                    if (group.Module!=null && group.Module.Count > 0)
                    {
                        for (int k = 0; k < group.Module.Count; k++)
                        {
                            ProjectMenuCommonElement it = group.Module[k];
                            TreeNode SubNode = new TreeNode();
                            SubNode.Text = it.Caption;
                            SubNode.Tag = ProjectUtil.TYPE_BILL_MODULE;
                            SubNode.ImageIndex = 7;
                            SubNode.SelectedImageIndex = 7;
                            SubNode.Name = it.Command;
                            node.Nodes.Add(SubNode);
                        }
                    }
                    ModTreeRoot.Nodes.Add(node);
                }
            }
            TreeRoot.Nodes.Add(ModTreeRoot);

            //添加仓库映射图形
            TreeNode MapTreeRoot = new TreeNode();
            MapTreeRoot.ImageIndex = 12;
            MapTreeRoot.SelectedImageIndex = 12;
            MapTreeRoot.Tag = ProjectUtil.TYPE_BILL_DATAMAP_ROOT;
            MapTreeRoot.Text = "库存表映射";
            if (MenuItem.MapProperties != null && MenuItem.MapProperties.Module != null && MenuItem.MapProperties.Module.Count > 0)
            {
                for (int i = 0; i < MenuItem.MapProperties.Module.Count; i++)
                {
                    ProjectMenuCommonElement it = MenuItem.MapProperties.Module[i];
                    TreeNode SubNode = new TreeNode();
                    SubNode.Text = it.Caption;
                    SubNode.Tag = ProjectUtil.TYPE_BILL_DATAMAP;
                    SubNode.ImageIndex = 7;
                    SubNode.SelectedImageIndex = 7;
                    SubNode.Name = it.Command;
                    MapTreeRoot.Nodes.Add(SubNode);
                }
            }
            TreeRoot.Nodes.Add(MapTreeRoot);


            //添加多样式表单
            TreeNode MultTreeRoot = new TreeNode();
            MultTreeRoot.ImageIndex = 6;
            MultTreeRoot.SelectedImageIndex = 6;
            MultTreeRoot.Tag = ProjectUtil.TYPE_BILL_MULTIPLE_ROOT;
            MultTreeRoot.Text = "多样式表单";
            if (MenuItem.MultipleProperties != null && MenuItem.MultipleProperties.MultipleProperties != null
                && MenuItem.MultipleProperties.MultipleProperties.Count > 0)
            {
                for (int i = 0; i < MenuItem.MultipleProperties.MultipleProperties.Count; i++)
                {
                    ProjectMenuCommonElement it = MenuItem.MultipleProperties.MultipleProperties[i];
                    TreeNode SubNode = new TreeNode();
                    SubNode.Text = it.Caption;
                    SubNode.Tag = ProjectUtil.TYPE_BILL_MULTIPLE;
                    SubNode.ImageIndex = 7;
                    SubNode.SelectedImageIndex = 7;
                    SubNode.Name = it.Command;
                    MultTreeRoot.Nodes.Add(SubNode);
                }
            }
            TreeRoot.Nodes.Add(MultTreeRoot);
            //添加工作流
            TreeNode WFlowTreeRoot = new TreeNode();
            WFlowTreeRoot.ImageIndex = 8;
            WFlowTreeRoot.SelectedImageIndex = 8;
            WFlowTreeRoot.Text = "工作审批流";
            WFlowTreeRoot.Tag = ProjectUtil.TYPE_BILL_WORKFLOW_ROOT;
            if (MenuItem.WorkFlow != null && MenuItem.WorkFlow.FlowNode != null
                && MenuItem.WorkFlow.FlowNode.Count > 0)
            {
                for (int i = 0; i < MenuItem.WorkFlow.FlowNode.Count; i++)
                {
                    ProjectMenuWFlowElement it = MenuItem.WorkFlow.FlowNode[i];
                    TreeNode SubNode = new TreeNode();
                    SubNode.Text = it.Caption;
                    SubNode.Tag = ProjectUtil.TYPE_BILL_WORKFLOW;
                    SubNode.ImageIndex = 7;
                    SubNode.SelectedImageIndex = 7;
                    SubNode.Name = it.Command;
                    WFlowTreeRoot.Nodes.Add(SubNode);
                }
            }
            TreeRoot.Nodes.Add(WFlowTreeRoot);

            //添加统计图形
            TreeNode ChartTreeRoot = new TreeNode();
            ChartTreeRoot.ImageIndex = 9;
            ChartTreeRoot.SelectedImageIndex = 9;
            ChartTreeRoot.Tag = ProjectUtil.TYPE_BILL_CHARTBAR_ROOT;
            ChartTreeRoot.Text = "图形统计表";

            if (MenuItem.ChartBar != null && MenuItem.ChartBar.ChartElement != null
                && MenuItem.ChartBar.ChartElement.Count > 0)
            {
                for (int i = 0; i < MenuItem.ChartBar.ChartElement.Count; i++)
                {
                    ProjectMenuCommonElement it = MenuItem.ChartBar.ChartElement[i];
                    TreeNode SubNode = new TreeNode();
                    SubNode.Text = it.Caption;
                    SubNode.Tag = ProjectUtil.TYPE_BILL_CHARTBAR;
                    SubNode.ImageIndex = 7;
                    SubNode.SelectedImageIndex = 7;
                    SubNode.Name = it.Command;
                    ChartTreeRoot.Nodes.Add(SubNode);
                }
            }
            TreeRoot.Nodes.Add(ChartTreeRoot);

            

            MenuTreeView.Nodes.AddRange(new TreeNode[] { TreeRoot });
            TreeRoot.Expand();
        }


        public bool SaveAllStatus
        {
            get
            {
                bool _TempSave = true;
                if (BillList.Count > 0)
                {
                    for(int i = 0; i < BillList.Count; i++)
                    {
                        ProjectUnitBillInterface unit = BillList[i];
                        if (!unit.SaveStatus)
                        {
                            _TempSave = false;
                            break;
                        }
                    }
                }
                return _TempSave;
            }
            set
            {
                RootForm.RefreshToolbar();
            }
        }

        public bool SaveStatus
        {
            get
            {
                bool _TempSave = true;
                if(ActiveBill!=null) { _TempSave = ActiveBill.SaveStatus; }
                return _TempSave;
            }
            set
            {
                RootForm.RefreshToolbar();
            }
        }

        public ProjectUnitBillInterface ActiveUnitRootPanel
        {
            get { return ActiveBill; }
            set { ActiveBill = value; }
        }

        public User UserInfo
        {
            get {  return user; } 
            set {  user = value; }
        }

        public HttpConnectUnit Http
        {
            get { return http; }
            set { http = value;  }
        }

        public ProjectMenuItem MenuItem
        {
            get { return menuItem; }
            set { menuItem = value; }
        }

        public ProjectVersionItem ProjectVersion
        {
            get { return projectVersion;}
            set { projectVersion = value; }
        }

        public void save()
        {
            if (ActiveBill != null)
            {
                ActiveBill.saveData(true);
            }
        }

        public void saveAll()
        {
            if (BillList.Count > 0)
            {
                for (int i = 0; i < BillList.Count; i++)
                {
                    ProjectUnitBillInterface unit = BillList[i];
                    if (!unit.isSubUnitBill)
                    {
                        unit.saveData(false);
                    }
                }
                RootForm.RefreshToolbar();
            }
        }

        /// <summary>
        /// 设置允许用户登录
        /// </summary>
        /// <param name="allow">true</param>
        public void allowLogin(bool allow)
        {
            #region 加载用户登录控制状态
            //查询登录限制状态
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("allow", "search");
            string content = http.GetHttp(ProjectUtil.HTTP_ALLOW_LOGIN_URL,param,"");// http.PostHttp(ProjectUtil.HTTP_ALLOW_LOGIN_URL, param, "text/xml");
            logger.Info(content);
            try
            {
                string this_status = "未知";
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(content);
                XmlNode node = doc.SelectSingleNode("error");
                if (node != null && node.HasChildNodes)
                {
                    XmlNode subNode = node.SelectSingleNode("result");
                    if (subNode != null)
                    {
                        if("当前状态"== subNode.InnerText)
                        {
                            subNode = node.SelectSingleNode("description");
                            if (subNode != null)
                            {
                                if("true" == subNode.InnerText)
                                {
                                    this_status = "允许登录";
                                }else if("false" == subNode.InnerText)
                                {
                                    this_status = "禁止登录";
                                }
                                if ("未知" != this_status)
                                {
                                    AllowForm form = new AllowForm("允许登录" == this_status,http);
                                    DialogResult dr = form.ShowDialog();
                                    if(dr == DialogResult.OK)
                                    {

                                    }
                                }
                                else
                                {
                                    AddConsoleText("当前登录状态获取失败", true);
                                }
                            }
                        }
                    }
                    
                }
            }
            catch {
                logger.Error(string.Format("解析xml失败:{0}", content));
                AddConsoleText("当前登录状态获取失败", true);
            }
            #endregion
        }

        /// <summary>
        /// 编译config
        /// </summary>
        public void compileConfig()
        {
            string back = http.AskCompileConfig();
            string alert = "";
            XmlDocument xml = new XmlDocument();
            try
            {
                xml.LoadXml(back);
                XmlElement root = xml.DocumentElement;
                XmlNode result = root.SelectSingleNode("result");
                string value = result.InnerText.Trim();
                alert = root.SelectSingleNode("description").InnerText;
                if (value == "0")
                {
                    AddConsoleText("编译成功", false);
                }
                else if (value == "1")
                {
                    AddConsoleText("会话超时,请重新登录",true);
                }
                else if(value== "2")
                {
                    AddConsoleText("编译功能被占用,请稍后尝试", true);
                }
                string[] list = alert.Split('\n');
                foreach(string text in list)
                {
                    AddConsoleText(text, false);
                }
            }catch(Exception e)
            {
                logger.Error("编译帐套加载返回值失败", e);
            }

        }
        /// <summary>
        /// 编译数据库
        /// </summary>
        public void compileDateBase()
        {
            string back = http.AskCompileDatabase();
            XmlDocument xml = new XmlDocument();
            string alert = "";
            try
            {
                xml.LoadXml(back);
                XmlElement root = xml.DocumentElement;
                XmlNode result = root.SelectSingleNode("result");
                string value = result.InnerText.Trim();
                alert = root.SelectSingleNode("description").InnerText;
                if (value == "0")
                {
                    AddConsoleText("编译成功", false);
                }
                else if (value == "1")
                {
                    AddConsoleText("会话超时,请重新登录", true);
                }
                else if (value == "2")
                {
                    AddConsoleText("编译功能被占用,请稍后尝试", true);
                }
                logger.Info(alert);
                string[] list = alert.Split('\n');
                foreach (string text in list)
                {
                    AddConsoleText(text, false);
                }
            }
            catch (Exception e)
            {
                logger.Error("编译帐套加载返回值失败", e);
            }
        }
        
        public void downLanguage(string filePath)
        {
            AddConsoleText(filePath, false);
            Http.FileLoadResources(ProjectUtil.HTTP_LGELOAD_URL, "", filePath, HttpConnectUnit.TYPE_CONFIG_ATTACH_FILE);
            if(File.Exists(filePath))ShowAlert("提示", "下载成功");

        }

        public void upLanguage(string filePath)
        {
            bool success = false;
            try
            {
                success = Http.FileUpLoadResources(ProjectUtil.HTTP_LGEUPLOAD_URL, "", filePath, HttpConnectUnit.TYPE_CONFIG_ATTACH_FILE);
                if(success) ShowAlert("提示", "上传成功");
            }
            catch (Exception ee)
            {
                ShowAlert("提示", "上传失败");
            }
        }

        public void AddConsoleText(string log, bool Error)
        {
            String info = string.Format("[{0}][{1}]-{2}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"), Error ? "Error" : "INFO", log);

            ListBoxConsole.Items.Add(info);
            ListBoxConsole.SelectedIndex = ListBoxConsole.ItemCount - 1;
        }

        /// <summary>
        /// 打开页面
        /// </summary>
        /// <param name="caption"></param>
        /// <param name="panel"></param>
        public void AddTabPage(string caption,ProjectUnitBillInterface panel,int index)
        {
            XtraTabPage page = new XtraTabPage();
            
            if (index != -1)
            {
                page.ImageIndex = index;
            }
            else
            {
                page.ImageIndex = 6;
            }
            page.Text = string.Format("{0}{1}",caption,panel.ReadOnly?"(只读)":"");
            page.Controls.Add((Control)panel);
            BillTabControl.TabPages.Add(page);
            BillTabControl.SelectedTabPage = page;
            ActiveBill = panel;
            BillList.Add(panel);
        }


        #region 事件注册区域


        private void TreePopOpenBill_Click(object sender, EventArgs e)
        {
            if (!loadding)
            {
                TreeNode node = MenuTreeView.SelectedNode;
                if (node != null && (node.Nodes == null || node.Nodes.Count == 0))
                {
                    int billType = (int)node.Tag;
                    if(billType == ProjectUtil.TYPE_DIC_MODULE
                        ||billType == ProjectUtil.TYPE_BILL_MODULE 
                        || billType == ProjectUtil.TYPE_BILL_DATAMAP
                        ||billType == ProjectUtil.TYPE_BILL_CHARTBAR
                        ||billType == ProjectUtil.TYPE_BILL_MULTIPLE)
                    {
                        EditModule(node.Name, node.Text, billType);
                    }
                    
                }
            }
            else
            {
                ShowAlert("提示", "当前正在加载配置,请稍后...");
            }

        }

        private void SearchControl_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void TreeBarRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }
        
        /// <summary>
        /// 复制选中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TbCCopySelected_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var text = ListBoxConsole.SelectedItem;
            if (text != null)
            {
                Clipboard.SetDataObject(text.ToString());

            }
        }

        private void TbCCopyAll_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            System.Text.StringBuilder text = new System.Text.StringBuilder();
            if (ListBoxConsole.Items.Count > 0)
            {
                for (int i = 0; i < ListBoxConsole.ItemCount; i++)
                {
                    text.Append(ListBoxConsole.Items[i].ToString()).AppendLine();
                }
            }
            if (text.Length > 0) Clipboard.SetDataObject(text.ToString());
        }

        private void TbCClearAll_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ListBoxConsole.Items.Clear();
        }

        private void TreePopMenu_Opening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            TreeNode node = MenuTreeView.SelectedNode;
            int nodeType = (int)node.Tag;
            TreePopDeleteBill.Enabled = true;
            TreePopNewDicBill.Enabled = true;
            if (nodeType == ProjectUtil.TYPE_DIC_MODULE_ROOT || nodeType == ProjectUtil.TYPE_DIC_MODULE)
            {

                TreePopNewDicBill.Text = "新建字典";
                if (nodeType == ProjectUtil.TYPE_DIC_MODULE_ROOT) { TreePopDeleteBill.Enabled = false; }

            }
            else if (nodeType == ProjectUtil.TYPE_BILL_MODULE_ROOT)
            {
                TreePopNewDicBill.Enabled = true;
                TreePopNewDicBill.Text = "新建分类";
                if (nodeType == ProjectUtil.TYPE_BILL_MODULE_ROOT) { TreePopDeleteBill.Enabled = false; }
            }
            else if (nodeType == ProjectUtil.TYPE_BILL_MODULE_GROUP || nodeType == ProjectUtil.TYPE_BILL_MODULE)
            {
                TreePopNewDicBill.Enabled = true;
                TreePopNewDicBill.Text = "新建单据";
            }
            else if (nodeType == ProjectUtil.TYPE_BILL_DATAMAP_ROOT || nodeType == ProjectUtil.TYPE_BILL_DATAMAP)
            {
                TreePopNewDicBill.Enabled = true;
                TreePopNewDicBill.Text = "新建映射";
                if (nodeType == ProjectUtil.TYPE_BILL_DATAMAP) { TreePopDeleteBill.Enabled = false; }
            }
            else if (nodeType == ProjectUtil.TYPE_BILL_MULTIPLE_ROOT || nodeType == ProjectUtil.TYPE_BILL_MULTIPLE)
            {
                TreePopNewDicBill.Enabled = true;
                TreePopNewDicBill.Text = "新建表单";
                if (nodeType == ProjectUtil.TYPE_BILL_MULTIPLE_ROOT) { TreePopDeleteBill.Enabled = false; }
            }
            else if (nodeType == ProjectUtil.TYPE_BILL_WORKFLOW_ROOT || nodeType == ProjectUtil.TYPE_BILL_WORKFLOW)
            {
                TreePopNewDicBill.Enabled = true;
                TreePopNewDicBill.Text = "新建审批";
                if (nodeType == ProjectUtil.TYPE_BILL_WORKFLOW_ROOT) { TreePopDeleteBill.Enabled = false; }
            }
            else if (nodeType == ProjectUtil.TYPE_BILL_CHARTBAR_ROOT || nodeType == ProjectUtil.TYPE_BILL_CHARTBAR)
            {
                TreePopNewDicBill.Enabled = true;
                TreePopNewDicBill.Text = "新建图形";
                if (nodeType == ProjectUtil.TYPE_BILL_CHARTBAR_ROOT) { TreePopDeleteBill.Enabled = false; }
            }
            else
            {
                TreePopNewDicBill.Enabled = false;
                TreePopDeleteBill.Enabled = false;
            }

        }

        private void TbTreeOpen_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            MenuTreeView.ExpandAll();
        }

        private void TbConll_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            MenuTreeView.CollapseAll();
            if (MenuTreeView.Nodes.Count > 0)
            {
                MenuTreeView.Nodes[0].Expand();
            }
        }

        private void SearchControl_Enter(object sender, EventArgs e)
        {

        }

        private void ListBoxConsole_DoubleClick(object sender, EventArgs e)
        {
            ListBoxConsole.Items.Clear();
        }

        private void TbRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            InitMenu();
        }

        private void MenuTreeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                MenuTreeView.SelectedNode = e.Node;
            }
        }

        private void MenuTreeView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (!loadding)
            {
                TreeNode node = MenuTreeView.SelectedNode;
                if (node != null && (node.Nodes == null || node.Nodes.Count == 0))
                {
                    int billType = (int)node.Tag;
                    if (billType == ProjectUtil.TYPE_BILL_MODULE 
                        || billType == ProjectUtil.TYPE_BILL_DATAMAP
                        || billType == ProjectUtil.TYPE_BILL_CHARTBAR
                        || billType == ProjectUtil.TYPE_BILL_MULTIPLE
                        || billType == ProjectUtil.TYPE_BILL_WORKFLOW
                        || billType == ProjectUtil.TYPE_DIC_MODULE
                        )
                    {
                        EditModule(node.Name, node.Text, billType);
                    }
                }
            }
            else
            {
                ShowAlert("提示", "当前正在加载配置,请稍后...");
            }
        }

        
        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BillTabControl_CloseButtonClick(object sender, EventArgs e)
        {
            XtraTabPage page = BillTabControl.SelectedTabPage;//XtraTabPage
            if (page != null)
            {
                ProjectUnitBillInterface BillControl = (ProjectUnitBillInterface)page.Controls[0];
                if (BillControl.close())
                {
                    //关闭子页面
                    int times = 0;
                    while (BillControl.SubjectPage!=null&&BillControl.SubjectPage.Count > 0)
                    {
                        if (times > 10) break;
                        //关闭其它子页面
                        for (int i = 0; i < BillTabControl.TabPages.Count; i++)
                        {
                            XtraTabPage SubPage = BillTabControl.TabPages[i];
                            ProjectUnitBillInterface SubControl = (ProjectUnitBillInterface)SubPage.Controls[0];
                            if (BillControl.ContainSubject(SubControl))
                            {
                                BillControl.RemoveSubjectBill(SubControl);
                                BillList.Remove(SubControl);
                                SubControl.ParentPage = null;
                                BillTabControl.TabPages.Remove(SubPage);
                                break;
                            }

                        }
                        times++;
                    }
                    if (BillControl.ParentPage != null)//去除父页面关系
                    {
                        BillControl.ParentPage.RemoveSubjectBill(BillControl);
                        BillControl.ParentPage = null;
                    }
                    BillList.Remove(BillControl);
                    BillTabControl.TabPages.Remove(page);
                }
                if (BillTabControl.TabPages.Count > 0)
                {
                    BillTabControl.SelectedTabPageIndex = BillTabControl.TabPages.Count - 1;
                }
            }
        }

        private void BillTabControl_SelectedPageChanged(object sender, TabPageChangedEventArgs e)
        {
            if (BillTabControl.TabPages.Count > 0)
            {
                XtraTabPage page = BillTabControl.SelectedTabPage;
                if(page.Controls[0] is ProjectUnitBillInterface)
                {
                    ActiveBill = (ProjectUnitBillInterface)page.Controls[0];
                }
            }
            else
            {
                ActiveBill = null;
            }
            RootForm.RefreshToolbar();
        }



        private void TreePopReLoad_Click(object sender, EventArgs e)
        {
            InitMenu();
        }

        
        /// <summary>
        /// 新建模块
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TreePopNewDicBill_Click(object sender, EventArgs e)
        {
            TreeNode node = MenuTreeView.SelectedNode;
            int nodeType = (int)node.Tag;

            if (nodeType == ProjectUtil.TYPE_DIC_MODULE_ROOT || nodeType == ProjectUtil.TYPE_DIC_MODULE)
            {
                TreeNode pNode = null;
                if (nodeType == ProjectUtil.TYPE_DIC_MODULE)
                {
                    pNode = node.Parent;
                }
                else
                {
                    pNode = node;
                }
                CreateModuleForm form = new CreateModuleForm(this, "字典", "");
                if (form.ShowDialog(RootForm) == DialogResult.OK)
                {
                    newBillMate(ProjectUtil.TYPE_DIC_MODULE, form.Key, form.Caption, "", pNode, null);
                }
            }
            else if (nodeType == ProjectUtil.TYPE_BILL_MODULE_ROOT)
            {
                CreateModuleForm form = new CreateModuleForm(this, "分类", "");
                if (form.ShowDialog(RootForm) == DialogResult.OK)
                {
                    newBillMate(ProjectUtil.TYPE_BILL_MODULE_ROOT, form.Key, form.Caption, "", node, null);
                }
            }
            else if (nodeType == ProjectUtil.TYPE_BILL_MODULE_GROUP || nodeType == ProjectUtil.TYPE_BILL_MODULE)//新建模块
            {
                string parentKey = "";
                string parentCaption = "";
                TreeNode PNode = null;
                if (nodeType == ProjectUtil.TYPE_BILL_MODULE_GROUP)
                {
                    PNode = node;
                    parentKey = node.Name;
                    parentCaption = node.Text;
                }
                else if (nodeType == ProjectUtil.TYPE_BILL_MODULE)
                {
                    PNode = node.Parent;
                    parentKey = PNode.Name;
                    parentCaption = PNode.Text;
                }
                //TreePopNewDicBill.Text = "新建单据";
                CreateModuleForm form = new CreateModuleForm(this, "单据", parentCaption);
                if (form.ShowDialog(RootForm) == DialogResult.OK)
                {
                    newBillMate(ProjectUtil.TYPE_BILL_MODULE, form.Key, form.Caption, parentKey, PNode, form.CopyForm);
                }
            }
            else if (nodeType == ProjectUtil.TYPE_BILL_MULTIPLE_ROOT || nodeType == ProjectUtil.TYPE_BILL_MULTIPLE)
            {
                TreeNode PNode = null;
                if (nodeType == ProjectUtil.TYPE_BILL_MULTIPLE)
                {
                    PNode = node.Parent;
                }
                else
                {
                    PNode = node;
                }
                //TreePopNewDicBill.Text = "新建表单";
                CreateModuleForm form = new CreateModuleForm(this, "表单", "");
                if (form.ShowDialog(RootForm) == DialogResult.OK)
                {
                    newBillMate(ProjectUtil.TYPE_BILL_MULTIPLE, form.Key, form.Caption, "", PNode, null);
                }
            }
            else if (nodeType == ProjectUtil.TYPE_BILL_WORKFLOW_ROOT || nodeType == ProjectUtil.TYPE_BILL_WORKFLOW)
            {
                TreeNode PNode = null;
                if (nodeType == ProjectUtil.TYPE_BILL_WORKFLOW)
                {
                    PNode = node.Parent;
                }
                else
                {
                    PNode = node;
                }
                //TreePopNewDicBill.Text = "新建审批";
                CreateModuleForm form = new CreateModuleForm(this, "审批", "");
                if (form.ShowDialog(RootForm) == DialogResult.OK)
                {
                    newBillMate(ProjectUtil.TYPE_BILL_WORKFLOW, form.Key, form.Caption, "", PNode, null);
                }
            }
            else if (nodeType == ProjectUtil.TYPE_BILL_CHARTBAR_ROOT || nodeType == ProjectUtil.TYPE_BILL_CHARTBAR)
            {
                TreeNode PNode = null;
                if (nodeType == ProjectUtil.TYPE_BILL_CHARTBAR)
                {
                    PNode = node.Parent;
                }
                else
                {
                    PNode = node;
                }
                //TreePopNewDicBill.Text = "新建图形";
                CreateModuleForm form = new CreateModuleForm(this, "图形", "");
                if (form.ShowDialog(RootForm) == DialogResult.OK)
                {
                    newBillMate(ProjectUtil.TYPE_BILL_CHARTBAR, form.Key, form.Caption, "", PNode, null);
                }
            }
            else if (nodeType == ProjectUtil.TYPE_BILL_DATAMAP || nodeType == ProjectUtil.TYPE_BILL_DATAMAP_ROOT)//仓库映射
            {
                TreeNode PNode = null;
                if (nodeType == ProjectUtil.TYPE_BILL_DATAMAP)
                {
                    PNode = node.Parent;
                }
                else
                {
                    PNode = node;
                }
                CreateModuleForm form = new CreateModuleForm(this, "映射", "");
                if (form.ShowDialog(RootForm) == DialogResult.OK)
                {
                    newBillMate(ProjectUtil.TYPE_BILL_DATAMAP, form.Key, form.Caption, "", PNode, null);
                }
            }
        }

        private void timerOver_Tick(object sender, EventArgs e)
        {
            InitMenu();
            timerOver.Enabled = false;
        }

        #endregion

        /// <summary>
        /// 弹出提示
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        public void ShowAlert(string title, string content)
        {
            AlertInfo info = new AlertInfo(title, content);
            info.Image = Properties.Resources.historyitem_32x32;
            Alert.Show(RootForm, info);
        }

        /// <summary>
        /// 打开脚本编辑器
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="bill"></param>
        /// <param name="js"></param>
        /// <returns></returns>
        public BillJscriptUnitPanel OpenJScriptPanel(ProjectUnitBillInterface parent, BillFormatModule bill, BillExpandJsCodeItem js)
        {
            BillJscriptUnitPanel jsPanel = new BillJscriptUnitPanel(bill, this, parent, js, bill.isReadOnly());
            jsPanel.Dock = DockStyle.Fill;
            AddTabPage(bill.getCaption() + "->" + js.Caption, jsPanel, 8);
            return jsPanel;
        }
        /// <summary>
        /// 打开扩展代码编辑器
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="bill"></param>
        /// <param name="js"></param>
        /// <returns></returns>
        public BillJavaUnitPanel OpenJavaPanel(ProjectUnitBillInterface parent, BillFormatModule bill, BillExpandJavaCodeItem js)
        {
            BillJavaUnitPanel panel = new BillJavaUnitPanel(bill, this, parent, js);
            panel.Dock = DockStyle.Fill;
            AddTabPage(bill.getCaption()+"->"+js.Caption, panel, 7);
            return panel;
        }

        /// <summary>
        /// 打开单据
        /// </summary>
        /// <param name="key"></param>
        /// <param name="caption"></param>
        /// <param name="type"></param>
        private void EditModule(string key, string caption, int type)
        {
            willOpenKey = key;
            willOpenCaption = caption;
            willOpenType = type;
            bool open = true;
            if (BillList.Count > 0)
            {
                for (int i = 0; i < BillList.Count; i++)
                {
                    ProjectUnitBillInterface unit = BillList[i];
                    if (!unit.isSubUnitBill)
                    {
                        if (unit.BillKey == key)
                        {
                            open = false;
                            break;
                        }
                    }
                }
            }
            if (open)
            {
                RootForm.ChangedCmdStatus(string.Format("正在打开模块[{0}],文件key[{1}]", caption,key));
                loadding = true; willReadOnly = true;
                http.AsyncResourcesXmlBean(key, caption, type, ref willReadOnly, null, LoadXmlBean);
            }
            else
            {
                ShowAlert("提示", "不可重复打开单据");
            }

        }
        /// <summary>
        /// 异步读取配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadXmlBean(object sender, PropertyDataEvent e)
        {
            int ThisThreadId = Thread.CurrentThread.ManagedThreadId;
            if (ThisThreadId != ThreadFormId)
            {
                BeginInvoke(new KEventHandler(LoadXmlBean), new object[] { sender, e });
            }
            else
            {
                if (e.Key == "OK")//加载成功
                {
                    string xml = e.Value as string;
                    
                    if (willOpenType == ProjectUtil.TYPE_PROJECT_MENU)//加载账套目录
                    {
                        JAXBContext<ProjectMenuItem> jaxb = new JAXBContext<ProjectMenuItem>();
                        try
                        {
                            MenuItem = jaxb.unmarshal(xml);
                        }
                        catch (Exception ee)
                        {
                            AddConsoleText(string.Format("加载目录数据异常:{0}", ee.Message), true);
                            logger.Error("加载目录数据异常", ee);
                        }
                        if (MenuItem != null)
                        {
                            ReLoadMenu();
                            AddConsoleText("帐套列表加载成功", false);
                            InitProjectVersion();
                        }
                    }
                    else if (willOpenType == ProjectUtil.TYPE_PROJECT_VERSION)//加载账套配置
                    {
                        JAXBContext<ProjectVersionItem> jaxb = new JAXBContext<ProjectVersionItem>();
                        ProjectVersionItem version = null;
                        try
                        {
                            version = jaxb.unmarshal(xml);
                        }
                        catch (Exception ee)
                        {
                            logger.Error("配置转换失败", ee);
                        }
                        if (version != null)
                        {
                            projectVersion = version;
                            AddConsoleText("帐套全局配置加载成功", false); ;
                        }
                    }
                    else if (willOpenType == ProjectUtil.TYPE_DIC_MODULE)//加载字典
                    {
                        BillDicModuleItem dic = null;
                        JAXBContext<BillDicModuleItem> jaxb = new JAXBContext<BillDicModuleItem>();
                        bool success = true;
                        try
                        {
                            dic = jaxb.unmarshal(xml);
                        }catch(Exception ee)
                        {
                            logger.Error("打开字典失败", ee);
                            success = false;
                        }
                        if (success && dic != null)
                        {
                            BillDictionaryUnitPanel bill = new BillDictionaryUnitPanel(this, dic, willReadOnly);
                            bill.Dock = DockStyle.Fill;
                            AddTabPage(dic.getCaption(), bill, 0);
                        }
                        
                    }
                    else if (willOpenType == ProjectUtil.TYPE_BILL_MODULE)//加载模块
                    {

                        BillModuleItem bean = null;
                        JAXBContext<BillModuleItem> jaxb = new JAXBContext<BillModuleItem>();
                        bool success = true;
                        try
                        {
                            bean = jaxb.unmarshal(xml);
                        }
                        catch (Exception ee)
                        {
                            logger.Error("打开模块失败:", ee);
                            success = false;
                        }
                        if (success && bean != null)
                        {
                            BillModuleControl bill = new BillModuleControl(bean, this, willReadOnly);
                            bill.Dock = DockStyle.Fill;
                            AddTabPage(bean.BillModule.Caption, bill, 6);
                        }
                    }
                    else if(willOpenType == ProjectUtil.TYPE_BILL_DATAMAP)//库存类型设置
                    {
                        BillDataMapItem bean = null;
                        JAXBContext<BillDataMapItem> jaxb = new JAXBContext<BillDataMapItem>();
                        bool success = true;
                        try
                        {
                            bean = jaxb.unmarshal(xml);
                        }
                        catch(Exception ee)
                        {
                            logger.Error("打开模块失败:", ee);
                            success = false;
                        }
                        if (success && bean != null)
                        {
                            BillMapUnitPanel bill = new BillMapUnitPanel(this, bean, willReadOnly);
                            bill.Dock = DockStyle.Fill;
                            AddTabPage(bean.MapProperties.Caption, bill, 9);
                        }
                    }
                    else if(willOpenType == ProjectUtil.TYPE_BILL_CHARTBAR)//加载图形统计表
                    {
                        BillChartModuleItem bean = null;
                        JAXBContext<BillChartModuleItem> jaxb = new JAXBContext<BillChartModuleItem>();
                        bool success = true;
                        try
                        {
                            bean = jaxb.unmarshal(xml);
                        }catch(Exception ee)
                        {
                            logger.Error("打开模块失败:", ee);
                            success = false;
                        }
                        if (success && bean != null)
                        {
                            BillChartUnitPanel bill = new BillChartUnitPanel(this, bean, willReadOnly);
                            bill.Dock = DockStyle.Fill;
                            AddTabPage(bean.getCaption(), bill, 10);
                        }
                    }else if(willOpenType == ProjectUtil.TYPE_BILL_MULTIPLE)//多样式表单
                    {
                        BillMultipleItem bean = null;
                        JAXBContext<BillMultipleItem> jaxb = new JAXBContext<BillMultipleItem>();
                        bool success = true;
                        try
                        {
                            bean = jaxb.unmarshal(xml);
                        }catch(Exception ee)
                        {
                            logger.Error("打开多样式表单失败", ee);
                            success = false;
                        }
                        if(success && bean != null)
                        {
                            BillMultipleUnitPanel bill = new BillMultipleUnitPanel(bean, this, willReadOnly);
                            bill.Dock = DockStyle.Fill;
                            AddTabPage(bean.getCaption(), bill, 11);
                        }
                    }
                    else if(willOpenType == ProjectUtil.TYPE_BILL_WORKFLOW)//工作流
                    {
                        WflowModuleItem bean = null;
                        JAXBContext<WflowModuleItem> jaxb = new JAXBContext<WflowModuleItem>();
                        bool success = true;
                        try
                        {
                            bean = jaxb.unmarshal(xml);
                        }
                        catch(Exception ee)
                        {
                            logger.Error("打开工作流表单失败", ee);
                            success = false;
                        }

                        if (success && bean != null)
                        {
                            BillWorkFlowPanel bill = new BillWorkFlowPanel(bean,this, willReadOnly);
                            bill.Dock = DockStyle.Fill;
                            AddTabPage(bean.getCaption(), bill, 12);
                        }
                    }
                    else if(willOpenType == ProjectUtil.TYPE_BILL_REFLECT)//数据反射
                    {
                        BillReflectModuleItem bean = null;
                        JAXBContext<BillReflectModuleItem> jaxb = new JAXBContext<BillReflectModuleItem>();

                        try
                        {
                            bean = jaxb.unmarshal(xml);
                        }
                        catch 
                        {
                            bean = new BillReflectModuleItem();
                            bean.ReflectRoot = new BillReflectModuleRoot();
                            bean.ReflectRoot.LastMender = user.UserName;
                            bean.ReflectRoot.LastModified = StringUtility.getZwStandLongDate();
                        }
                        if (bean != null)
                        {
                            BillReflectUnitPanel panel = new BillReflectUnitPanel(bean, this, willReadOnly);
                            panel.Dock = DockStyle.Fill;
                            AddTabPage("数据反射配置", panel, 13);
                        }

                    }

                }
                else
                {
                    AddConsoleText("加载配置异常:" + e.Value.ToString(), true);
                }
                RootForm.WaitCmdStatus();
                willOpenCaption = "";
                willOpenKey = "";
                willReadOnly = false;
                loadding = false;
            }
        }

        /// <summary>
        /// 新建单据
        /// </summary>
        /// <param name="billType"></param>
        /// <param name="key"></param>
        /// <param name="caption"></param>
        /// <param name="parent"></param>
        private void newBillMate(int billType,string key,string caption,string parent, TreeNode pNode,object clone)
        {
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("kt_billName", key);
            param.Add("kt_caption", caption);
            param.Add("kt_operate", ProjectUtil.SAFETY_OPERATE_NEW);
            param.Add("kt_parentPath", parent);
            param.Add("kt_imgUrl", "");
            param.Add("kt_billType", Convert.ToString(billType));
            XmlDocument xmlDoc = new XmlDocument();
            bool success = true;
            try
            {
                string xml = http.PostHttp(ProjectUtil.HTTP_SAFETY_URL, param, "");
                
                try
                {
                    xmlDoc.LoadXml(xml);
                }
                catch(Exception e)
                {
                    success = false;
                    logger.Error(e);
                    ShowAlert("异常", "返回值格式不正确:"+e.StackTrace);
                }
            }
            catch(Exception e)
            {
                success = false;
                logger.Error("创建表单异常", e);
                ShowAlert("异常", "连接服务器连接失败");
            }
            if (success)
            {
                XmlElement root =  xmlDoc.DocumentElement;
                XmlNode result = root.SelectSingleNode("result");
                string language = "";
                if (result != null)
                {
                    XmlNode des = root.SelectSingleNode("description");
                    string description = des != null ? des.InnerText : "";
                    if (result.InnerText != "0")
                    {
                        ShowAlert("提示", description);
                        return;
                    }
                    XmlNode lang = root.SelectSingleNode("language");
                    language = lang != null ? lang.InnerText : "";
                }
                else
                {
                    ShowAlert("提示", "返回值格式不正确:"+xmlDoc.OuterXml);
                    return;
                }
                if(billType == ProjectUtil.TYPE_DIC_MODULE)
                {
                    TreeNode node = new TreeNode();
                    node.SelectedImageIndex = 7;
                    node.ImageIndex = 7;
                    node.Text = caption;
                    node.Name = key;
                    node.Tag = ProjectUtil.TYPE_DIC_MODULE;
                    pNode.Nodes.Add(node);

                    BillDicModuleItem dic = new BillDicModuleItem();
                    dic.RootProperties = new BillDicModuleRoot();
                    dic.RootProperties.Caption = caption;
                    dic.RootProperties.Key = key;
                    dic.RootProperties.LanguageTexts = language;
                    dic.RootProperties.OwnerProperties = new BillModuleOwner();
                    dic.RootProperties.OwnerProperties.Creater = user.UserName;
                    dic.RootProperties.OwnerProperties.Created = StringUtility.getZwStandLongDate();
                    dic.RootProperties.OwnerProperties.LastMender = user.UserName;
                    dic.RootProperties.OwnerProperties.LastModified = StringUtility.getZwStandLongDate();
                    dic.FieldsProperties = new BillDicModuleFieldsRoot();
                    dic.FieldsProperties.Fields = new List<com.bean.xml.RootInterface.Field.BillUiFieldsItem>();

                    BillDictionaryUnitPanel bill = new BillDictionaryUnitPanel(this, dic, false);
                    bill.Dock = DockStyle.Fill;
                    AddTabPage(dic.getCaption(), bill, 0);
                    bill.SaveStatus = false;

                }
                else if (billType == ProjectUtil.TYPE_BILL_MODULE_ROOT)//新建分类
                {
                    TreeNode group = new TreeNode();
                    group.Text = caption;
                    group.Tag = ProjectUtil.TYPE_BILL_MODULE_GROUP;
                    group.Name = key;
                    pNode.Nodes.Add(group);
                }
                else if(billType == ProjectUtil.TYPE_BILL_MODULE)//新建模块
                {

                    TreeNode node = new TreeNode();
                    node.SelectedImageIndex = 7;
                    node.ImageIndex = 7;
                    node.Text = caption;
                    node.Name = key;
                    node.Tag = ProjectUtil.TYPE_BILL_MODULE;
                    pNode.Nodes.Add(node);

                    BillModuleItem bean = null;
                    if (clone!=null&&clone is BillModuleItem)
                    {
                        bean = clone as BillModuleItem;
                        bean.BillModule = new BillModuleRoot();
                        bean.BillModule.Caption = caption;
                        bean.BillModule.Key = key;
                        bean.BillModule.LanguageTexts = language;
                        bean.BillModule.JavaPackage = key.ToLower();
                        bean.BillModule.Behavior = new BillModuleBehavior();
                        bean.BillModule.Advanced = new BillModuleAdvanced();
                        bean.BillModule.Owner = new BillModuleOwner();
                        bean.BillModule.Owner.Creater = user.UserName;
                        bean.BillModule.Owner.Created = StringUtility.getZwStandLongDate();
                        bean.BillModule.Owner.LastMender = user.UserName;
                        bean.BillModule.Owner.LastModified = StringUtility.getZwStandLongDate();
                        bean.updateLanguage();
                        JClipboard.Clear();//清空复制区域
                    }
                    else
                    {
                        bean = new BillModuleItem();
                        bean.BillModule = new BillModuleRoot();
                        bean.BillModule.Caption = caption;
                        bean.BillModule.Key = key;
                        bean.BillModule.LanguageTexts = language;
                        bean.BillModule.JavaPackage = key.ToLower();
                        bean.BillModule.Behavior = new BillModuleBehavior();
                        bean.BillModule.Advanced = new BillModuleAdvanced();
                        bean.BillModule.Owner = new BillModuleOwner();
                        bean.BillModule.Owner.Creater = user.UserName;
                        bean.BillModule.Owner.Created = StringUtility.getZwStandLongDate();
                        bean.BillModule.Owner.LastMender = user.UserName;
                        bean.BillModule.Owner.LastModified = StringUtility.getZwStandLongDate();
                        bean.UiField = new BillUiGroupRoot();
                        bean.UiField.FieldsProperties = new List<BillUiGroupItems>();

                        //默认创建一个字段组
                        BillUiGroupItems group = new BillUiGroupItems();
                        group.Key = "TableMain";
                        group.Caption = "主要信息";
                        bean.UiField.addNode(group, bean);
                    }

                    BillModuleControl bill = new BillModuleControl(bean, this, false);
                    bill.Dock = DockStyle.Fill;
                    AddTabPage(bean.BillModule.Caption, bill, 6);
                    bill.SaveStatus = false;
                }
                else if(billType == ProjectUtil.TYPE_BILL_DATAMAP)//新建库存映射
                {

                    TreeNode node = new TreeNode();
                    node.SelectedImageIndex = 7;
                    node.ImageIndex = 7;
                    node.Text = caption;
                    node.Name = key;
                    node.Tag = ProjectUtil.TYPE_BILL_DATAMAP;
                    pNode.Nodes.Add(node);

                    BillDataMapItem map = new BillDataMapItem();
                    map.MapProperties = new BillDataMapRoot();
                    map.MapProperties.Key = key;
                    map.MapProperties.Caption = caption;
                    map.MapProperties.LanguageTexts = language;
                    map.MapProperties.JavaPackage = key.ToLower();
                    map.MapProperties.Compress = false;
                    map.MapProperties.Advanced = new BillDataMapAdvanced();
                    map.MapProperties.Advanced.Field = new List<BillDataMapAdvancedElement>();
                    map.MapProperties.Owner = new BillModuleOwner();
                    map.MapProperties.Owner.Creater = user.UserName;
                    map.MapProperties.Owner.Created = StringUtility.getZwStandLongDate();
                    map.MapProperties.Owner.LastMender = user.UserName;
                    map.MapProperties.Owner.LastModified = StringUtility.getZwStandLongDate();

                    map.GroupProperties = new BillDataMapGroupRoot();
                    map.GroupProperties.FieldsProperties = new List<BillDataMapGroupItem>();

                    BillMapUnitPanel bill = new BillMapUnitPanel(this, map, false);
                    bill.Dock = DockStyle.Fill;
                    AddTabPage(map.MapProperties.Caption, bill, 9);
                    bill.SaveStatus = false;
                }
                else if(billType == ProjectUtil.TYPE_BILL_MULTIPLE)//新建多样式表单
                {
                    TreeNode node = new TreeNode();
                    node.SelectedImageIndex = 7;
                    node.ImageIndex = 7;
                    node.Text = caption;
                    node.Name = key;
                    node.Tag = ProjectUtil.TYPE_BILL_MULTIPLE;
                    pNode.Nodes.Add(node);

                    BillMultipleItem item = new BillMultipleItem();
                    item.MultProperties = new BillModuleRoot();
                    item.MultProperties.Key = key;
                    item.MultProperties.Caption = caption;
                    item.MultProperties.LanguageTexts = language;
                    item.MultProperties.JavaPackage = key.ToLower();
                    item.MultProperties.Owner = new BillModuleOwner();
                    item.MultProperties.Owner.Creater = user.UserName;
                    item.MultProperties.Owner.Created = StringUtility.getZwStandLongDate();
                    item.MultProperties.Owner.LastMender = user.UserName;
                    item.MultProperties.Owner.LastModified = StringUtility.getZwStandLongDate();
                    item.ParamProperties = new BillMultipleParamRoot();
                    item.UiField = new BillUiGroupRoot();
                    item.UiField.FieldsProperties = new List<BillUiGroupItems>();

                    BillMultipleUnitPanel bill = new BillMultipleUnitPanel(item, this, false);
                    bill.Dock = DockStyle.Fill;
                    AddTabPage(item.getCaption(), bill, 11);
                    bill.SaveStatus = false;

                }
                else if(billType == ProjectUtil.TYPE_BILL_CHARTBAR)//新建图形统计表
                {
                    TreeNode node = new TreeNode();
                    node.SelectedImageIndex = 7;
                    node.ImageIndex = 7;
                    node.Text = caption;
                    node.Name = key;
                    node.Tag = ProjectUtil.TYPE_BILL_DATAMAP;
                    pNode.Nodes.Add(node);

                    BillChartModuleItem item = new BillChartModuleItem();
                    item.ChartProperties = new BillChartModuleInfoRoot();
                    item.ChartProperties.Key = key;
                    item.ChartProperties.Caption = caption;
                    item.ChartProperties.LanguageTexts = language;
                    item.ChartProperties.JavaPackage = key.ToLower();
                    item.ChartProperties.Advanced = new BillChartModuleAdvanced();
                    item.ChartProperties.Owner = new BillModuleOwner();
                    item.ChartProperties.Owner.Creater = user.UserName;
                    item.ChartProperties.Owner.Created = StringUtility.getZwStandLongDate();
                    item.ChartProperties.Owner.LastMender = user.UserName;
                    item.ChartProperties.Owner.LastModified = StringUtility.getZwStandLongDate();
                    item.FieldProperties = new BillChartModuleFieldsRoot();
                    item.ExpandCode = new BillExpandCodeRoot();
                    item.ExpandCode.JavaPlugin = new BillExpandJavaCodeRoot();
                    BillChartUnitPanel bill = new BillChartUnitPanel(this, item, false);
                    bill.Dock = DockStyle.Fill;
                    AddTabPage(item.getCaption(), bill, 10);
                    bill.SaveStatus = false;
                }
                else if(billType == ProjectUtil.TYPE_BILL_WORKFLOW)//新建工作流
                {
                    TreeNode node = new TreeNode();
                    node.SelectedImageIndex = 7;
                    node.ImageIndex = 7;
                    node.Text = caption;
                    node.Name = key;
                    node.Tag = ProjectUtil.TYPE_BILL_WORKFLOW;
                    pNode.Nodes.Add(node);

                    WflowModuleItem item = new WflowModuleItem();
                    item.Workflow = new WflowModuleRoot();
                    item.Workflow.Key = key;
                    item.Workflow.Caption = caption;
                    item.Workflow.LanguageTexts = language;
                    item.Workflow.JavaPackage = key.ToLower();
                    item.Workflow.FlowField = new WflowFieldElement();
                    item.Workflow.FlowLimit = new WflowLimitElement();
                    item.Workflow.OwnerProperties = new WflowOwnerElement();
                    item.Workflow.OwnerProperties.Creater = user.UserName;
                    item.Workflow.OwnerProperties.Created = StringUtility.getZwStandLongDate();
                    item.Workflow.OwnerProperties.LastMender = user.UserName;
                    item.Workflow.OwnerProperties.LastModified = StringUtility.getZwStandLongDate();
                    item.FlowNode = new com.bean.xml.WorkFlow.Node.WflowModuleNodeRoot();
                    item.FlowNode.FlowCommandNode = new List<com.bean.xml.WorkFlow.Node.WflowModuleNodeItem>();
                    //添加固定开始和结束
                    WflowModuleNodeItem begin = new WflowModuleNodeItem();
                    begin.Key = "begin";
                    begin.Caption = "开始";
                    begin.NodeType = WflowUtility.NODE_TYPE_START_UP_FLOW;
                    begin.Top = 20;begin.Left = 20;
                    item.FlowNode.addNode(begin, item);

                    WflowModuleNodeItem end = new WflowModuleNodeItem();
                    end.Key = "end";
                    end.Caption = "结束";
                    end.NodeType = WflowUtility.NODE_TYPE_FINISH_FLOW;
                    end.Top = 300;end.Left = 20;
                    item.FlowNode.addNode(end, item);
                    item.FlowEvent = new com.bean.xml.WorkFlow.WflowModuleEventRoot();

                    BillWorkFlowPanel panel = new BillWorkFlowPanel(item, this, false);
                    panel.Dock = DockStyle.Fill;
                    AddTabPage(item.getCaption(), panel, 12);
                    panel.SaveStatus = false;
                }
            }


        }

        
        /// <summary>
        /// 复制模块
        /// </summary>
        public void copyBill()
        {
            object tag;
            bool rs = ActiveBill.Copy(out tag);
            if (!rs||tag == null)
            {
                ShowAlert("提示", "当前单据不支持复制");
            }else
            {
                JClipboard.copy(new object[] { tag });
                AddConsoleText("复制模块成功", false);
            }
        }
        /// <summary>
        /// 删除模块
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TreePopDeleteBill_Click(object sender, EventArgs e) 
        {
            TreeNode node = MenuTreeView.SelectedNode;
            int nodeType = (int)node.Tag;
            string xml = "";
            bool success = false;
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("kt_billName", node.Name);
            param.Add("kt_caption", node.Text);
            param.Add("kt_operate", ProjectUtil.SAFETY_OPERATE_DELETE);
            param.Add("kt_parentPath", "");
            param.Add("kt_imgUrl", "");
            param.Add("kt_billType", Convert.ToString(nodeType));

            if(nodeType == ProjectUtil.TYPE_DIC_MODULE)//删除字典
            {
                if (XtraMessageBox.Show(string.Format("您确认要删除字典[{0}]吗？", node.Text), "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    try
                    {
                        xml = http.PostHttp(ProjectUtil.HTTP_SAFETY_URL, param, "");
                        success = true;
                    }
                    catch (Exception ee)
                    {
                        success = false;
                        AddConsoleText("连接服务器异常", true);
                        logger.Error(ee);
                    }
                }
            }
            else if (nodeType == ProjectUtil.TYPE_BILL_MODULE)//删除模块
            {
                if(XtraMessageBox.Show(string.Format("您确认要删除模块[{0}]吗？",node.Text),"提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Question) == DialogResult.OK)
                {
                    try
                    {
                        xml = http.PostHttp(ProjectUtil.HTTP_SAFETY_URL, param, "");
                        success = true;
                    }
                    catch(Exception ee)
                    {
                        success = false;
                        AddConsoleText("连接服务器异常", true);
                        logger.Error(ee);
                    }
                }
            }
            else if(nodeType == ProjectUtil.TYPE_BILL_MODULE_GROUP)//删除分组
            {
                if (node.Nodes.Count > 0)
                {
                    ShowAlert("提示", "当前分组下存在模块,不能删除");
                }
                else
                {
                    if (XtraMessageBox.Show(string.Format("您确认要删除模块分组[{0}]吗？", node.Text), "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                    {
                        try
                        {
                            param["kt_billType"] = Convert.ToString(ProjectUtil.TYPE_BILL_MODULE_ROOT);//替换为此标识
                            xml = http.PostHttp(ProjectUtil.HTTP_SAFETY_URL, param, "");
                            success = true;
                        }
                        catch (Exception ee)
                        {
                            success = false;
                            AddConsoleText("连接服务器异常", true);
                            logger.Error(ee);
                        }
                    }
                }
            }
            if (success)
            {
                XmlDocument xmlDoc = new XmlDocument();
                try
                {
                    xmlDoc.LoadXml(xml);
                    XmlElement root = xmlDoc.DocumentElement;
                    XmlNode docNode = root.SelectSingleNode("description");
                    string description = "返回结果异常";
                    if (docNode != null)
                    {
                        description = docNode.InnerText;
                    }
                    if(description == "成功删除")
                    {
                        node.Remove();
                    }
                    ShowAlert("提示", description);
                }
                catch(Exception ee)
                {
                    logger.Info(xml);
                    AddConsoleText("返回值Xml格式化异常", true);
                    logger.Error("返回值Xml格式化异常",ee);
                }
            }
        }

       
        /// <summary>
        /// 打开反射配置
        /// </summary>
        public void OpenReflectBill()
        {
            EditModule("ProjectReflectCfg", "数据反射配置", ProjectUtil.TYPE_BILL_REFLECT);
        } 
    }
}
